﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Web;

namespace BfLib.Web
{
    public class QueryStringParser
    {
        public static string AddParameter(string QueryString, string ParamName, string ParamValue)
        {
            NameValueCollection nvc = HttpUtility.ParseQueryString(QueryString);
         
            if (nvc.Get(ParamName) != null)
            {
                nvc[ParamName] = ParamValue;
            }
            else
            {
                nvc.Add(ParamName, ParamValue);
            }

            List<String> items = new List<String>();
            foreach (string s in nvc.Keys)
            {
                items.Add(String.Format("{0}={1}", s, HttpUtility.UrlEncode(nvc[s])));
            }

            return String.Join("&", items.ToArray<string>());
        }

        public static string RemoveParameter(string QueryString, string ParamName)
        {
            NameValueCollection nvc = HttpUtility.ParseQueryString(QueryString);
            nvc.Remove(ParamName);

            List<String> items = new List<String>();
            foreach (string s in nvc.Keys)
            {
                items.Add(String.Format("{0}={1}", s, nvc[s]));
            }

            return String.Join("&", items.ToArray<string>());
        }

        public static bool ContainsParameter(string QueryString, string ParamName)
        {
            NameValueCollection nvc = HttpUtility.ParseQueryString(QueryString);
            return nvc.Get(ParamName) != null;
        }

        public static string GetParameter(string QueryString, string ParamName)
        {
            NameValueCollection nvc = HttpUtility.ParseQueryString(QueryString);

            if (nvc.Get(ParamName) != null)
            {
                return nvc[ParamName];
            }
            else
            {
                return null;
            }
        }
    }
}
